package cn.fzkj.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class NettyServer {

    /**
     * 服务端代码相对固定
     */
    public static void main(String[] args) {
        // 负责处理连接（主线程池）
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        // 负责处理读写（从线程池） ，线程数使用默认的：cpu核心数 * 2
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        // 辅助创建netty服务端的引导类
        ServerBootstrap serverBootstrap = new ServerBootstrap();

//        serverBootstrap.group(); // 单线程模型
//        serverBootstrap.group(workerGroup); // 多线程模型
        serverBootstrap.group(bossGroup, workerGroup) // 主从模型
                .channel(NioServerSocketChannel.class)  // 通道的处理类型
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        // 编码器和解码器的作用：将ByteBuf类型的数据转成String，将String转成ByteBuf
                        // netty传输的是ByteBuf类型的
                        pipeline.addLast(new StringEncoder()); // 编码器
                        pipeline.addLast(new StringDecoder()); // 解码器
                        // 添加自定义处理器
                        pipeline.addLast(new ChannelHandler());
                    }
                });
        try {
            ChannelFuture future = serverBootstrap.bind(6666).sync();
            System.out.println("netty server started.");

            // 阻塞，监听关闭信号，等待客户端请求
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            System.out.println("exception.");
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}
